package com.mssh.login.config;

import com.mssh.login.core.JwtFilter;
import com.mssh.login.core.JwtRealm;
import com.mssh.login.core.RedisManager;
import com.mssh.login.mapper.SysUserMapper;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.crazycake.shiro.IRedisManager;
import org.crazycake.shiro.RedisCacheManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import javax.servlet.Filter;
import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 熳殊沙华
 * @Date: 2025/03/25/12:17
 * @Description:
 */
@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class ShiroConfig {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private AuthConfig authConfig;

    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    @Bean
    public IRedisManager redisManager() {
        return new RedisManager(redisConnectionFactory);
    }

    @Bean
    public CacheManager cacheManager() {
        // 使用Redis缓存
        RedisCacheManager cacheManager = new RedisCacheManager();
        cacheManager.setRedisManager(redisManager()); // 需自定义RedisManager
        cacheManager.setExpire(1800); // 缓存过期时间（秒）
        return cacheManager;
    }

    /**
     * 创建自定义realm对象
     * @return 自定义realm独享
     */
    @Bean("jwtRealm")
    public JwtRealm jwtRealm(){
        JwtRealm realm = new JwtRealm(sysUserMapper);
        realm.setCredentialsMatcher(hashedCredentialsMatcher());
        return realm;
    }

    // 安全管理器
    @Bean("securityManager")
    public DefaultWebSecurityManager securityManager() {
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        manager.setRealm(jwtRealm());
        manager.setCacheManager(cacheManager()); // 关联缓存管理器
        return manager;
    }

    /**
     * shiro过滤器管理
     * @return
     */
    @Bean("shiroFilterFactoryBean")
    public ShiroFilterFactoryBean shiroFilterFactoryBean(){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //指定权限管理器
        shiroFilterFactoryBean.setSecurityManager(securityManager());
        //过滤器
        shiroFilterFactoryBean.setFilters(this.getFilters());

        //过滤器链
        Map<String, String> map = new HashMap<>();
        /**
         * anon: 无需认证就能访问（过滤器）
         * authc: 必须认证才能访问
         * user: 必须拥有 记住我 才能用
         * perms: 拥有对某个资源的权限才能访问
         * role: 拥有某个角色权限才能访问
         */
        map.put("/auth/login","anon");
        map.put("/auth/captcha","anon");
//        屏蔽注册接口
//        map.put("/register","anon");
        map.put("/js/**","anon");
        map.put("/css/**","anon");
        map.put("/image/**","anon");
        map.put("/headerImg/**","anon");
        //所有请求都需要经过jwt认证过滤器
        map.put("/**", "jwt");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        return shiroFilterFactoryBean;
    }

    // 配置密码加密策略（例如 SHA-256 + 盐值）
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName("SHA-256");
        matcher.setHashIterations(2048); // 提高迭代次数
        matcher.setStoredCredentialsHexEncoded(true); // 根据实际存储格式调整
        return matcher;
    }

    /**
     * 获取自定义的shiro过滤器
     * @return
     */
    private Map<String, Filter> getFilters(){
        Map<String, Filter> filterMap = new HashMap<String, Filter>();
        // 添加自己的过滤器并且取名为jwt
        filterMap.put("jwt", new JwtFilter(redisTemplate, authConfig));
        return filterMap;
    }

    /**
     * aop增强，使用注解方式鉴权
     * @return
     */
    @Bean
    public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
        advisorAutoProxyCreator.setProxyTargetClass(true);
        return advisorAutoProxyCreator;
    }


    /**
     * 配合进行权限效验
     * @return
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor getAuthorizationAttributeSourceAdvisor(){
        AuthorizationAttributeSourceAdvisor aasa = new AuthorizationAttributeSourceAdvisor();
        aasa.setSecurityManager(securityManager());
        return aasa;
    }
}
